#!/bin/bash
#
# ec2-get-credentials - Retrieve the ssh credentials and add to authorized_keys
#
# Based on /usr/local/sbin/ec2-get-credentials from Amazon's ami-20b65349
#

prog=$(basename $0)
logger="logger -t $prog"

public_key_url=http://169.254.169.254/1.0/meta-data/public-keys/0/openssh-key
public_key_file=/tmp/openssh_id.pub
public_key_ephemeral=/mnt/openssh_id.pub
authorized_keys=/root/.ssh/authorized_keys

# Wait for the network to come up.
perl -MIO::Socket::INET -e '
 until(new IO::Socket::INET("169.254.169.254:80")){print"Waiting for network...\n";sleep 1}
' | $logger

# Try to get the ssh public key from instance data.
curl --silent --fail -o $public_key_file $public_key_url
test -d /root/.ssh || mkdir -p -m 700 /root/.ssh
if [ $? -eq 0 -a -e $public_key_file ] ; then
  if ! grep -s -q -f $public_key_file $authorized_keys
  then
    cat $public_key_file >> $authorized_keys
    $logger "New ssh key added to $authorized_keys from $public_key_url"
  fi
  chmod 600 $authorized_keys
  rm -f $public_key_file

# Try to get the ssh public key from ephemeral storage
elif [ -e $public_key_ephemeral ] ; then
  if ! grep -s -q -f $public_key_ephemeral $authorized_keys
  then 
    cat $public_key_ephemeral >> $authorized_keys
    $logger "New ssh key added to $authorized_keys from $public_key_ephemeral"
  fi
  chmod 600 $authorized_keys
  chmod 600 $public_key_ephemeral
fi
